package com.gexin.model.order;

import com.gexin.common.utils.SQLUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.order.base.BaseOrderInvoice;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

/**
 * 业务名称:  t_order_invoice(订单发票表) 
 */
@SuppressWarnings("serial")
public class OrderInvoice extends BaseOrderInvoice<OrderInvoice> {
	public static final OrderInvoice dao = new OrderInvoice();
	/** 未开票*/
	public static final Integer STATE_SUBMIT = 1;
	/** 已开票*/
	public static final Integer STATE_FINISH = 2;

	/**类型 个人发票*/
	public static final Integer TYPE_USER = 1;
	/**类型 公司发票*/
	public static final Integer TYPE_COMPANY = 2;

	public Page<OrderInvoice> findList(Integer page , Integer pageSize , String id , Integer state,String times) {
		SQLUtils sql = new SQLUtils();
		sql.append(" from t_order_invoice where 1=1 ");
		if(id!=null)
			sql.whereLike("id",id.toString());
		if(state!=null){
			sql.whereEquals("state",state);
		}
		if(!StringUtil.isBlank(times)){
			String[] split = times.split(" - ");
			if(split!=null&&split.length==2)
				sql.between("create_time",split[0],split[1]);
		}
		sql.append(" order by create_time desc");
		return paginate(page,pageSize,"select * ",sql.toString());
	}

	public List<OrderInvoice> findByOrderInvoice(OrderInvoice o) {
		SQLUtils sql = new SQLUtils("select toi.*,item.*,");
		sql.append(" tor.express_address,tor.express_phone" );
		sql.append(" from t_order_invoice toi " );
		sql.append(" LEFT JOIN t_order tor ON tor.id=toi.id ");
		sql.append(" LEFT JOIN ");
		sql.append(" (select tor.id as order_id, ");
		sql.append(" GROUP_CONCAT(pro.product_name) as product_names, ");
		sql.append(" GROUP_CONCAT(IF(ISNULL(toim.sku_text) || LENGTH(trim(toim.sku_text))<1,'无',toim.sku_text)) as sku_names, ");
		sql.append(" GROUP_CONCAT(toim.unit_price) AS unit_price, ");
		sql.append(" GROUP_CONCAT(toim.nums) AS nums, ");
		sql.append(" GROUP_CONCAT(toim.price) AS price, ");
		sql.append(" GROUP_CONCAT(pro.product_tag) AS product_tag ");
		sql.append(" from t_order tor ");
		sql.append(" LEFT JOIN t_order_item toim on tor.id=toim.order_id ");
		sql.append(" LEFT JOIN t_products pro on toim.product_id = pro.id ");
		sql.append(" GROUP BY tor.id) item ON item.order_id=tor.id ");

		sql.append(" where 1=1 ");
		if (o!=null){
			if (o.getState()!=null);
			sql.whereEquals("toi.state",o.getState());
		}
		return find(sql.toString());

	}

	public List<OrderInvoice> findByCreateTime(String[] split) {
		return	find("Select * from t_order_invoice where state=1 and create_time between ? and ?",split[0],split[1]);
	}
}
